import pandas as pd
import chardet

# 检测文件编码
file_path = 'train.csv'

with open(file_path, 'rb') as f:
    result = chardet.detect(f.read())
encoding = result['encoding']
print(f"检测到的编码: {encoding}")

# 使用检测到的编码读取 CSV 文件
try:
    train_data = pd.read_csv(file_path, encoding=encoding)
    print("成功读取 CSV 文件")
except UnicodeDecodeError:
    print(f"使用编码 {encoding} 读取失败")

# 检查数据前几行
print(train_data.head())

import matplotlib.pyplot as plt
import seaborn as sns

# 指定中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 查看数据基本信息
print(train_data.info())
print(train_data.describe())

# 检查缺失值
missing_values = train_data.isnull().sum()
print("Missing values in each column:\n", missing_values)

# 计算相关性矩阵
correlation_matrix = train_data.corr()

# 可视化相关性矩阵
plt.figure(figsize=(14, 12))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")
plt.title('Correlation Matrix')
plt.show()

# 提取与洪水发生概率相关性最高和最低的指标
flood_probability_correlation = correlation_matrix['洪水概率']
print("Top 5 positively correlated features:\n", flood_probability_correlation.nlargest(6))
print("Top 5 negatively correlated features:\n", flood_probability_correlation.nsmallest(5))


